package com.yuanli.cosmeticmirror.utils;

import android.content.Context;
import android.database.Cursor;
import android.os.Environment;
import android.provider.MediaStore;

import com.yuanli.cosmeticmirror.base.Config;
import com.yuanli.cosmeticmirror.base.Constant;
import com.yuanli.cosmeticmirror.base.MyApp;
import com.yuanli.cosmeticmirror.bean.UserWork;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

public class MusicUtil {
    private static String TAG = "MusicUtil";
    private File file; // 文件根目录
    private File tempFile; // 临时文件,保存下载的文件,每次下载过后,清空

    /**
     * 构造文件处理工具类 - 播放音频文件
     * @param context
     */
    public MusicUtil(Context context) {
        // 音频播放的缓存文件 构造文件根目录
        file = new File(CommonUtils.getCacheFilePath(MyApp.getInstance(), Constant.MUSIC));
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    /**
     * 判断本地是否有指定url音频文件的缓存文件
     *
     * @param url 音频文件url
     * @return 缓存文件路径, 如果不存在则返回null
     */
    public String exists(String url) throws IOException {
        // 截取地址, 获取缓存音频文件的名称
        String fileName = url.substring(url.lastIndexOf("/") + 1);
        // 构建文件
        tempFile = new File(file, fileName);
        // 如果文件存在,则返回文件路径,如果文件不存在则返回null并且创建文件
        if (tempFile.exists()) {
            return tempFile.getAbsolutePath();
        } else {
            tempFile.createNewFile(); // 创建音频文件
            return null;
        }
    }

    /**
     * 保存音频文件
     *
     * @param is InputStream
     */
    public void saveFile(InputStream is) throws IOException {
        // 构建文件输出流
        FileOutputStream fos = new FileOutputStream(tempFile);
        // 构建缓冲区
        byte[] b = new byte[1024];
        // 循环读取数据
        int byteCount; // 每次读取的长度
        while ((byteCount = is.read(b)) != -1) {
            // 将每次读取的数据保存到文件当中
            fos.write(b, 0, byteCount);
        }
        fos.close(); // 关闭文件输出流
        is.close(); // 关闭输入流
    }

    /**
     * 获取sd卡所有的音频文件
     * m4a = audio/mp4a-latm
     * flac = audio/flac
     * wma = audio/x-ms-wma
     * mp3 = audio/mpeg, audio/x-mpeg
     * aac = audio/aac
     * wav = audio/x-wav, audio/wav
     *
     * @param context
     * @param page 从1开始
     * @param context
     * @return
     * @throws Exception
     */
    private static final String[] SUPPORT_DECODE_AUDIO_FORMAT = {"audio/mp4a-latm", "audio/flac", "audio/x-ms-wma", "audio/mpeg", "audio/x-mpeg", "audio/aac", "audio/x-wav", "audio/wav"};

    private static final String[] SUPPORT_DECODE_AUDIO_FORMAT_MP3 = {"audio/x-mpeg", "audio/mpeg"};

    /**
     * 查找所有本地音乐
     * @param context
     * @param minMusicSecond
     * @param isSearchAllAudioFormat 是否查找所有音频格式
     * @return
     */
    public static ArrayList<UserWork> getAllLocalMusic(Context context,
                                                       int minMusicSecond,
                                                       boolean isSearchAllAudioFormat) {
        String[] supportAudioFormat;
        if (isSearchAllAudioFormat) {
            supportAudioFormat = SUPPORT_DECODE_AUDIO_FORMAT;
        } else {
            supportAudioFormat = SUPPORT_DECODE_AUDIO_FORMAT_MP3;
        }

        ArrayList<UserWork> audios = new ArrayList<>();

        StringBuilder selectionBuilder = new StringBuilder();
        int size = supportAudioFormat.length;
        for (int i = 0; i != size; ++i) {
            selectionBuilder.append("mime_type=? or ");
        }
        int sbLen = selectionBuilder.length();
        selectionBuilder.delete(sbLen - 3, sbLen);

        final String selection = selectionBuilder.toString();

        Cursor cursor = context.getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[]{
                        //MediaStore.Audio.Media._ID,
                        MediaStore.Audio.Media.DISPLAY_NAME,
                        MediaStore.Audio.Media.TITLE,
                        MediaStore.Audio.Media.DURATION,
                        //MediaStore.Audio.Media.ARTIST,
                        //MediaStore.Audio.Media.MIME_TYPE,
                        MediaStore.Audio.Media.DATE_MODIFIED,
                        MediaStore.Audio.Media.DATE_ADDED,
                        MediaStore.Audio.Media.SIZE,
                        MediaStore.Audio.Media.DATA},
                selection, supportAudioFormat, null);

        if (cursor == null){ return audios; }
        if (cursor.moveToFirst()) {
            do {
                //过滤不存在音频
                String audioPath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                if (!FileUtils.isFileExists(audioPath)){
                    continue;
                }
                //long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
                String audioName = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
                //String audioTitle = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
                //String singer = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
                int audioDuration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
                long audioSize = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));
                //String format = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.MIME_TYPE));

                long lastModifyTime = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATE_MODIFIED));
                long addTime = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATE_ADDED));

                UserWork audioEntry = new UserWork();
                //id
                //audioEntry.setAudioId(id);
                // 文件名(带后缀)
                audioEntry.setaName(audioName);
                //音频名称（不带后缀）
                //audioEntry.setaName(audioTitle);
                // 时长
                audioEntry.setDuration(audioDuration);
                // 文件路径
                audioEntry.setaPath(audioPath);
                // 歌手名
                //audioEntry.setSinger(singer);
                // 文件大小
                audioEntry.setaSizeStr(FileUtils.getFileSize(audioPath));
                //格式
                //audioEntry.setAudioFormat(getFormat(audioName));

                //最后修改时间
                if (lastModifyTime == -1){
                    lastModifyTime = addTime;
                }
                audioEntry.setaLastModifyTime(lastModifyTime);

                if (!"".equals(audioName) && audioDuration > (minMusicSecond * 1000)){
                    audios.add(audioEntry);
                }

            } while (cursor.moveToNext());
            cursor.close();
        }
        return audios;
    }

    private static String getFormat(String str){
        int index = str.indexOf(".");
        if (index != -1){
            return str.substring(index+1);
        }
        return str;
    }

}